package cn.net.xyan.yypt.controller


import cn.net.xyan.blossom.kotlin.StatusAndMessageError
import cn.net.xyan.blossom.kotlin.qrCode
import cn.net.xyan.yypt.dao.PayOrderDao
import cn.net.xyan.yypt.entity.PayOrder
import cn.net.xyan.yypt.service.LinkingCloudOpenApi
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import java.io.ByteArrayOutputStream

import javax.imageio.ImageIO

@Controller
@RequestMapping("/public")
class QRCodeController {

    @Autowired
    lateinit var linkingCloudOpenApi: LinkingCloudOpenApi

    @Autowired
    lateinit var payOrderDao:PayOrderDao

    @RequestMapping("/qrCode")
    @ResponseBody
    fun qrCode(@RequestParam("value")value:String): HttpEntity<ByteArray> {


        val image = value.qrCode

        val output = ByteArrayOutputStream()

        ImageIO.write(image,"png",output)

        val data = output.toByteArray()

        val header = HttpHeaders()


        header.set("Content-Type", MediaType.IMAGE_PNG_VALUE)

        //header.set("Content-Disposition", "inline; filename=$fileName")
        header.contentLength = data.size.toLong()

        return HttpEntity(data, header)
    }


    @RequestMapping("/orderQrCode/{orderID}")
    @ResponseBody
    fun payOrderQRCode(@PathVariable(name = "orderID")orderID:String): HttpEntity<ByteArray> {

        var payOrder: PayOrder = payOrderDao.findOne(orderID) ?: throw StatusAndMessageError("没有查到订单${orderID}")

        val image = payOrder.attach?.qrCode

        val output = ByteArrayOutputStream()

        ImageIO.write(image,"png",output)

        val data = output.toByteArray()

        val header = HttpHeaders()


        header.set("Content-Type", MediaType.IMAGE_PNG_VALUE)

        //header.set("Content-Disposition", "inline; filename=$fileName")
        header.contentLength = data.size.toLong()

        return HttpEntity(data, header)
    }
}